package com.imax.center.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.imax.center.common.Result;
import com.imax.center.constant.CommonConstants;
import com.imax.center.model.amap.AddressComponentDTO;
import com.imax.center.service.AmapService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

import java.util.List;

/**
 * 高德地图服务实现类
 */
@Slf4j
@Service
public class AmapServiceImpl implements AmapService {
    
    /**
     * 高德地图API Key
     */
    @Value("${amap.key}")
    private String amapKey;
    
    @Autowired
    private RestTemplate restTemplate;

    /**
     * 根据经纬度获取行政区划信息
     *
     * @param longitude 经度
     * @param latitude  纬度
     * @return 行政区划信息
     */
    @Override
    public Result<AddressComponentDTO> getAddressByLocation(String longitude, String latitude) {
        try {
            // 构建请求URL
            String location = longitude + "," + latitude;
            String url = UriComponentsBuilder.fromHttpUrl(CommonConstants.RE_GEOCODE_URL)
                    .queryParam("key", amapKey)
                    .queryParam("location", location)
                    .build()
                    .toUriString();
            
            // 发送请求获取结果
            String responseJson = restTemplate.getForObject(url, String.class);

            // 解析响应结果
            JSONObject response = JSON.parseObject(responseJson);
            String status = response.getString("status");
            
            if (!"1".equals(status)) {
                String infoCode = response.getString("infocode");
                String info = response.getString("info");
                log.error("高德地图API请求失败，infocode: {}, info: {}", infoCode, info);
                return Result.error("获取地址信息失败：" + info);
            }
            
            // 解析地址组件
            JSONObject regeocode = response.getJSONObject("regeocode");
            JSONObject addressComponent = regeocode.getJSONObject("addressComponent");
            String formattedAddress = regeocode.getString("formatted_address");
            
            // 构建返回结果
            AddressComponentDTO dto = new AddressComponentDTO();
            dto.setCountry(addressComponent.getString("country"));
            dto.setProvince(addressComponent.getString("province"));
            dto.setCity(addressComponent.getString("city"));
            dto.setDistrict(addressComponent.getString("district"));
            dto.setAdcode(addressComponent.getString("adcode"));
            dto.setAddress(formattedAddress);
            
            return Result.success(dto);
        } catch (Exception e) {
            log.error("获取高德地图行政区划信息异常", e);
            return Result.error("获取地址信息异常：" + e.getMessage());
        }
    }

    @Override
    public Result<Object> getLonAndLatByAddress(String address, String city) {
        HttpEntity<Object> entity = new HttpEntity<>(null, null);
        String url = CommonConstants.GEOCODE_URL + "?address=" + address + "&city=" + city + "&key=" + amapKey;
        ResponseEntity<JSONObject> exchange = restTemplate.exchange(url, HttpMethod.GET, entity, JSONObject.class);
        if (ObjectUtils.isNotEmpty(exchange) && HttpStatus.OK.equals(exchange.getStatusCode())) {
            JSONObject body = exchange.getBody();
            assert body != null;
            String infocode = body.getString("infocode");
            if (infocode != null && infocode.equals("10000")) {
                List<JSONObject> geocodes = body.getJSONArray("geocodes").toJavaList(JSONObject.class);
                if (geocodes != null && geocodes.size() > 0) {
                    return Result.success(geocodes.get(0));
                }
            }
        }
        return Result.error("获取经纬度失败");
    }
} 